package org.lalib.controller.action;

import java.util.ArrayList;
import java.util.List;

import org.lalib.acquire.IControllerAction;
import org.lalib.command.CommandPageCommand;
import org.lalib.entity.object.ECategory;
import org.lalib.entity.object.EFood;
import org.lalib.entity.object.EHistoricalValue;
import org.lalib.entity.object.EItem;
import org.lalib.entity.object.EUser;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Scope("request")
@Controller("cItemEditAction")
public class CItemEditAction extends CAbstractItemOperationAction implements IControllerAction {

	private static final long serialVersionUID = 1L;

	@Override
	public String init(EItem item) {
		cItemEditForm.clean();
		item = refreshItem(item);
		List<ECategory> itemCategories = item.getCategories();
		itemCategories = getAllCategoriesWithParents(itemCategories);
		List<String> tabNames = cVariableService.getUniqueTabNamesForGivenVariables(itemCategories);
		cItemEditForm.setTabNames(tabNames);
		cItemEditForm.setItem(item);
		return "itemEdit";
	}

	private EItem refreshItem(EItem item) {
		if (item instanceof EUser)
			return cUserService.getUserById(item.getId());
		else if (item instanceof EFood)
			return cFoodService.getFoodById(item.getId());
		else
			return cTableService.getTableById(item.getId());
	}

	private List<ECategory> getAllCategoriesWithParents(List<ECategory> itemCategories) {
		List<ECategory> categories = new ArrayList<>();

		for (ECategory category : itemCategories) {
			categories.addAll(cCategoryService.getAllParentCategoriesForGivenCategory(category));
			categories.add(category);
		}

		categories = cCategoryService.filterUniqueCategories(categories);
		return categories;
	}

	@Override
	@SuppressWarnings("rawtypes")
	public String save() {
		EItem item = cItemEditForm.getItem();
		String name = item.getName();
		item = getRefreshedItem(item);
		item.setName(name);
		List<EHistoricalValue> eHistoricalValues = getValuesFromMap(cItemEditForm.getHistoricalValueMap());
		List<EHistoricalValue> strippedValues = cHistoricalValueService.getStrippedValues(item, eHistoricalValues);
		save(item);
		cHistoricalValueService.save(strippedValues);
		cItemEditForm.clean();
		return new CommandPageCommand(item).execute();
	}

	@Override
	public String cancel() {
		cItemEditForm.clean();
		return "";
	}
}